const jwt = require('jsonwebtoken');
module.exports = () => {
    return async (ctx,next) => {
        //1.排除不需要的检验接口  登录  注册
        //2.获取token  判断是否携带token
        //3.jwt.verify 

        let writePath = ['/api/registry','/api/login'];

        if(writePath.includes(ctx.path)){  // /api/detail?id=1   ctx.url  ctx.path(不携带?后的参数)  /api/detail
            await next();
        }else{
            //获取token 
            let token = ctx.get('token');

            if(token){

                try{
                    jwt.verify(token,'lixd');
                    await next();
                }catch(e){
                    if(e.name === 'JsonWebTokenError' || e.name === 'TokenExpiredError'){
                        ctx.status = 401;
                        ctx.body = {
                            code:4,
                            msg:e
                        }
                    }else{
                        ctx.body = {
                            code:0,
                            msg:e
                        }
                    }
                    
                }
            }else{
                ctx.body = {
                    code:4,
                    msg:'鉴权失败'
                }
            }
        }
    }
}